const jwt = require('jsonwebtoken');
const db = require('../db/db');
const config = require('../config');

// 认证中间件
exports.authenticate = async (req, res, next) => {
  try {
    // 从请求头获取认证信息
    const authHeader = req.headers.authorization;
    
    if (!authHeader) {
      return res.status(401).json({
        success: false,
        message: '未提供认证头'
      });
    }
    
    // 分割Bearer令牌
    const parts = authHeader.split(' ');
    
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
      return res.status(401).json({
        success: false,
        message: '认证格式无效，应为: Bearer [token]'
      });
    }
    
    const token = parts[1];
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供认证令牌'
      });
    }

    // 验证JWT令牌
    try {
      const decoded = jwt.verify(token, config.jwtSecret);
      
      // 检查令牌包含的会话ID是否在数据库中有效
      const sessionRows = await db.query(
        'SELECT user_id FROM user_sessions WHERE token = ? AND expires_at > NOW()',
        [decoded.sessionId]
      );
      
      if (!sessionRows || sessionRows.length === 0) {
        return res.status(401).json({
          success: false,
          message: '令牌已过期或已失效'
        });
      }

      // 将用户信息添加到请求对象
      req.user = {
        id: decoded.userId,
        username: decoded.username
      };

      next();
    } catch (jwtError) {
      console.error('JWT验证错误:', jwtError);
      return res.status(401).json({
        success: false,
        message: '无效的令牌',
        error: jwtError.message
      });
    }
  } catch (error) {
    console.error('认证错误:', error);
    res.status(500).json({
      success: false,
      message: '认证过程中发生错误'
    });
  }
};
